import {useUserStore} from '@/stores/user'

interface ChatMessage {
  id: any,
  time: Date | number;
  type: any;
  value: any
}

const userId = useUserStore().userinfo.userId
// const key = `chat_message_${userId}:${friendId}`
/**
 * 
 * @param friendId 用户id
 * @param message 消息内容
 * @param type 消息类型
 */
export function saveMessage(friendId: any, id: any, message: any, type: any) {
  const key = `chat_message_${userId}:${friendId}`
  const list: ChatMessage[] = JSON.parse(localStorage.getItem(key) || "[]")
  let newMessage = {
    id,
    time: new Date,
    type: type,
    value: message
  }
  list.push(newMessage)
  localStorage.setItem(key, JSON.stringify(list))
}

/**
 * 
 * @param friendId 用户id
 * @returns 获取userId用户的聊天记录
 */
export function listMessage(friendId: any) : ChatMessage[] {
  const key = `chat_message_${userId}:${friendId}`
  return JSON.parse(localStorage.getItem(key) || "[]")
}

/**
 * 
 * @param friendId 用户id
 * @param start 开始时间
 * @param end 结束时间
 * @returns 
 */
export function listMessageByRange(friendId: any, start: Date|number, end: Date|number) {
  const key = `chat_message_${userId}:${friendId}`
  
  let list: ChatMessage[] = JSON.parse(localStorage.getItem(key) || "[]")
  return list.filter(item => {
    return item.time >= start && item.time <= end
  })
}

/**
 * 
 * @param userId 用户id
 * @param start 开始时间
 * @returns 
 */
export function listMessageByDate(friendId: any, start: Date|number) {
  const key = `chat_message_${userId}:${friendId}`
  let list: ChatMessage[] = JSON.parse(localStorage.getItem(key) || "[]")
  return list.filter(item => {
    return item.time >= start
  })
}